#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
import sys
import json

reload(sys)
sys.setdefaultencoding('utf8')

class Medicine(object):
    def __init__(self, db_charset = 'utf8'):
        self.__config = self.__loadConfig()
        self.__cursor = self.__connectDB(db_charset)

    def __del__(self):
        self.__cursor.close()

    def __loadConfig(self):
        try:
            fp = open('./settings.json', 'r')
        except FileOperateError, e:
            print 'open config error'

        config = fp.read()
        config = json.loads(config)

        fp.close()

        return config

    def __connectDB(self, db_charset):
        try:
            db = MySQLdb.connect(
                host = self.__config['hostname'],
                user = self.__config['username'],
                passwd = self.__config['password'],
                db = self.__config['db_name'],
                charset = db_charset
            )
        except DatabaseError, e:
            print 'connect database failed'

        return db.cursor()

    def getAllMedicines(self):
        # 使用execute方法执行SQL语句
        self.__cursor.execute("SELECT `mm_id`, `medicine_name` FROM `medicine_medicaments` WHERE `is_del`=0")

        # 使用 fetchone() 方法获取一条数据库。
        medicines = self.__cursor.fetchall()

        # self.__cursor.close()

        return_medicines = {}

        for item_med in medicines:
            return_medicines[str(item_med[0])] = item_med[1]

        return return_medicines

    def getAllAnagraphs(self, str_origin):
        if str_origin:
            # 使用execute方法执行SQL语句
            self.__cursor.execute("SELECT `ma_id`, `anagraph_name`, `anagraph_origin` FROM `medicine_anagraphs` WHERE `anagraph_origin`= '%s' AND `is_del`=0" % (str_origin))
        else:
            self.__cursor.execute("SELECT `ma_id`, `anagraph_name`, `anagraph_origin` FROM `medicine_anagraphs` WHERE `is_del`=0")
        # 使用 fetchone() 方法获取一条数据库。
        anagraphs = self.__cursor.fetchall()

        # self.__cursor.close()

        return_anagraphs = {}

        for item_ana in anagraphs:
            if str(item_ana[2]) == '伤寒杂病论':
                return_anagraphs[str(item_ana[0])] = item_ana[1]
            elif str(item_ana[2]) == '金匮要略':
                return_anagraphs[str(item_ana[0])] = item_ana[1]
            elif str(item_ana[2]) == '肘后备急方':
                return_anagraphs[str(item_ana[0])] = item_ana[1]
            elif str(item_ana[2]) == '备急千金要方':
                return_anagraphs[str(item_ana[0])] = item_ana[1]

        return return_anagraphs

    def getAllAnagraphComposes(self, str_origin):
        # 使用execute方法执行SQL语句
        self.__cursor.execute("SELECT `ma_id`, `mm_id` FROM `medicine_anagraph_composes` WHERE `is_del`=0 AND `need_modify`=0")

        # 使用 fetchone() 方法获取一条数据库。
        composes = self.__cursor.fetchall()

        # self.__cursor.close()

        all_anagrphs = self.getAllAnagraphs(str_origin)
        all_medicines = self.getAllMedicines()

        return_composes = {}

        for item_com in composes:
            item_ana_name = all_anagrphs.get(str(item_com[0]))
            item_med_name = all_medicines.get(str(item_com[1]))

            if item_ana_name and item_med_name:
                if not return_composes.has_key(item_ana_name):
                    return_composes[item_ana_name] = []

                return_composes[item_ana_name].append(item_med_name)

        return return_composes
